<template>
  <div>
    <el-card>
      <!-- 提示行 -->
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        center
        :closable="false"
      ></el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="parseInt(activeIndex)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-position="top"
        status-icon
      >
        <!-- 标签页 -->
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :beforeLeave="beforeTabsLeave"
          @tab-click="tabClick"
        >
          <!-- 基本信息的内容 -->
          <el-tab-pane label="基本信息" name="0">
            <!-- 基本信息表单 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="goodsCatList"
                :props="goodsCatProps"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 复选框 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="o"
                  border
                  v-for="(o, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              label="主体-商品名称"
              v-for="item in this.onlyTabData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action是图片要上传的后台API地址 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
            >
              <el-button type="primary" size="mini">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add" class="addbtn"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 点击已上传图片的对话框 -->
    <el-dialog
      :visible.sync="handlePreviewDialogVisible"
      title="图片预览"
      width="50%"
    >
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import _ from "lodash";
export default {
  data() {
    return {
      // value: [],
      options: [],
      // 当前激活的步骤条
      activeIndex: "0",
      // 商品属性表单的实例对象
      goodTypeForm: {},
      // 添加商品的表单
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      // 添加商品的校验规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" },
        ],
      },
      // 添加商品分类的级联选择器props属性
      goodsCatProps: {
        // 实现鼠标hover
        expandTrigger: "hover",
        // 指定选项的值为选项对象的某个属性值
        value: "cat_id",
        // 指定选项标签为选项对象的某个属性值
        label: "cat_name",
        children: "children",
      },
      // 级联选择器选中的项
      // selectKeys: [],
      // 级联选择器的数据源
      goodsCatList: [],
      // 标签页的sel属性设置
      good_sel: "",
      // 商品动态参数的数据
      manyTabData: [],
      // 商品静态属性的数据
      onlyTabData: [],
      // 已上传文件的列表
      fileList: [],
      // 上传图片地址
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 为upload组件设置请求头的对象
      headersObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 控制点击预览对话框
      handlePreviewDialogVisible: false,
      // 对话框的图片路径
      dialogImageUrl: "",
    };
  },
  created() {
    // 获取所有的商品分类列表
    this.getGoodsCatList();
  },
  methods: {
    // 更改级联选择器的事件
    handleChange() {
      console.log(this.addForm.goods_cat);
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        console.log(this.addForm.goods_cat.length);
      }
    },
    // 获取级联选择器数据
    async getGoodsCatList() {
      const { data: res } = await this.$http.get("categories");
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.goodsCatList = res.data;
      this.$message({
        type: "success",
        message: res.meta.msg,
      });
    },
    // 控制标签页之前切换的操作
    beforeTabsLeave(activeName, oldActiveName) {
      // console.log('离开前的标签页名字:'+oldActiveName);
      // console.log('离开后的标签页名字:'+activeName);
      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类！");
        return false;
      }
    },
    // 点击标签页标签的回调函数
    tabClick() {
      if (this.activeIndex == "1") {
        this.good_sel = "many";
      } else if (this.activeIndex == "2") {
        this.good_sel = "only";
      }
      console.log(this.activeIndex);
      axios
        .get(`categories/${this.catId}/attributes`, {
          params: { sel: this.good_sel },
        })
        .then(({ data: res }) => {
          // console.log(res);
          if (this.good_sel == "many") {
            this.getAttrVals(res.data);
            this.manyTabData = res.data;
            console.log(this.manyTabData, "this.manyTabData");
          } else if (this.good_sel == "only") {
            this.onlyTabData = res.data;
            console.log(this.onlyTabData, "2222");
          }
        })
        .catch((error) => error);
    },
    // 将attr_vals的字符串类型转换为数组形式
    getAttrVals(arr) {
      arr.forEach((item) => {
        // console.log(item.attr_vals.split(","), "1111");
        item.attr_vals =
          item.attr_vals.length === 0 ? [] : item.attr_vals.split(",");
        // console.log(item, "0000");
      });
    },
    // 点击已上传文件的钩子
    handlePreview(file) {
      console.log(file, 111);
      // this.dialogImageUrl = this.uploadURL.concat(file.response.data.tmp_path);
      this.dialogImageUrl = file.response.data.url;
      this.handlePreviewDialogVisible = true;
      console.log(this.dialogImageUrl);
    },
    // 点击删除文件的钩子
    handleRemove(file) {
      // 1.先获取将要移除的文件路径
      const fileinfo = file.response.data.tmp_path;
      console.log(file);
      this.addForm.pics = this.addForm.pics.filter((x) => x.pic !== fileinfo);
      console.log(this.addForm);
      /* // 第一种方法 */
      // 2.从数组pics中查找到将要移除文件的索引值
      //  const i = this.addForm.pics.findIndex(x=>
      //   x.pic === fileinfo
      //   )
      //   console.log(i);
      //   // 3.调用数组pics的splice方法，将索引删除
      //   this.addForm.pics.splice(i,1)
      /* // 第二种方法 */
      //直接使用数组的filter筛选不符合条件的
      // this.addForm.pics = this.addForm.pics.filter((x) => x.pic !== fileinfo);
      // console.log(this.addForm);
    },
    //第一种直接 上传成功后的操作:将图片信息保存在pics数组中
    handleSuccess(response) {
      console.log(response);
      this.addForm.pics.push({ pic: response.data.tmp_path });
      console.log(this.addForm);
    },
    /* //间接方法 handleSuccess(response) {
      console.log(response);
      // 1.先拼接成对象{'pic':'地址'}
      const picInfo = { pic: response.data.tmp_path };
      // 2.将拼接好的对象push到数组pics中
      this.addForm.pics.push(picInfo);
      console.log(this.addForm);
    }, */
    add() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) {
          return this.$message.error("请正确完成表单信息");
        }
        const form = JSON.parse(JSON.stringify(this.addForm));
        // const form = _.cloneDeep(this.addForm);
        // 将addform的数组转化为字符串
        form.goods_cat = form.goods_cat.join(",");
        // 将动态、静态id和vals转化为addform的attrs
        this.manyTabData.forEach((item) => {
          const attrobj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          };
          this.addForm.attrs.push(attrobj);
        });
        console.log(this.onlyTabData, 88888);
        this.onlyTabData.forEach((item) => {
          const attrobj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addForm.attrs.push(attrobj);
        });
        form.attrs = this.addForm.attrs;
        // 将goods_introduce中的标签去掉
        form.goods_introduce = this.addForm.goods_introduce.replace(/<.*?>/gi,"");
        console.log(form, "scv");
        axios
          .post(`goods`, form)
          .then(({ data: res }) => {
            console.log(res);
            if (res.meta.status !== 201) {
              this.$message.error(res.meta.msg);
            } else {
              this.$router.push("/goods");
              this.$message.success(res.meta.msg);
            }
          })
          .catch(() => {
            this.$message.error(res.meta.msg);
          });
      });
    },
    // 去除字符串中的html标签
    // delHtmlTag(str) {
    //   return str.replace(/<[^>]+>/g, "");
    // },
  },

  computed: {
    catId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },
};
</script>

<style lang="scss" scoped>
$small: 13px;
$large: 14px;
.el-card {
  padding: 10px;
  .el-steps {
    font-size: $small;
    margin: 15px 0;
  }
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.addbtn {
  margin-top: 15px;
}
</style>